/*
收据9
*/
<template xmlns:el-col="http://www.w3.org/1999/html">
  <div class="app-page">
    <!-- 操作菜单区 -->
    <my-header>
      <el-button @click="handleBeforeUpdate" v-repeatClick>修改</el-button>
      <el-button @click="getInvoice" v-repeatClick>刷新</el-button>
    </my-header>

    <!-- 列表区 -->
    <el-card style="flex: 1;">
      <div class="app-page">
        <div class="content-flex">
          <div>
            <el-form ref="search" :model="search" inline size="small">
              <el-form-item label="" prop="info">
                <el-input placeholder="收据号/运单号/销售单号" v-model="search.info"></el-input>
              </el-form-item>
              <el-form-item label="" prop="receiptStatus">
                <el-select clearable v-model="search.receiptStatus" placeholder="收据状态" style="width: 100px">
                  <el-option v-for="item in baseFormOptions.status" :key="item" :value="item" :label="item"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="创建日期" prop="date">
                <el-date-picker v-model="search.date" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="">
                <el-button type="primary" @click="searchPage">搜索</el-button>
                <el-button type="warning" @click="$refs.search.resetFields()">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <!-- 列表区 -->
        <div style="flex: 1">
          <el-table height="100%" :data="data" border stripe highlight-current-row ref="multipleTable"
            @row-dblclick="handleRowDbclick" @row-click="handleRowClick" @selection-change="handleSelectionChange">
            <el-table-column type="index" width="55" align="center">
            </el-table-column>
            <el-table-column type="selection" width="55" align="center">
            </el-table-column>
            <el-table-column label="收据号" width="300">
              <template slot-scope="scope">
                <el-link @click="handleRowDbclick(scope.row)">{{ scope.row.receiptInfo.receiptCode }} </el-link>
                <span style="margin-left:10px">
                  <span :style="{ color: getInvoiceStatus(scope.row.receiptInfo.receiptStatus) }">({{
                    scope.row.receiptInfo.receiptStatus }})</span>
                </span>
                <div v-if="scope.row.receiptInfo.receiptStatus === '未结清'">
                  已收：{{ scope.row.receiptInfo.paidAmount }}
                  <span style="margin-left:10px">
                    待收：{{ scope.row.receiptInfo.unPaidAmount }}
                  </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="单号" width="250">
              <template slot-scope="scope">
                <div v-if="scope.row.receiptOrderInfos.length > 1">共{{ scope.row.receiptOrderInfos.length }}单</div>
                <div v-if="scope.row.receiptOrderInfos.length === 0">共0单</div>
                <div style="line-height: 25px" v-for="(item, index) in scope.row.receiptOrderInfos.slice(0, 2)"
                  :key="item.id">
                  <span>{{ item.orderCode }} <span
                      v-if="index === 1 && scope.row.receiptOrderInfos.length > 2">...</span></span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="费用核算" width="250">
              <template slot-scope="scope">
                <div v-if="formatAmount(scope.row.receiptCostInfo).length > 1">
                  <div>
                    应收总额：{{ scope.row.receiptInfo.receiveAbleAmount }}
                    <span v-if="scope.row.receiptInfo.discount != 100">
                      (手写折扣：{{ scope.row.receiptInfo.discount + '%' }})
                    </span>
                  </div>
                  <div v-for="item in formatAmount(scope.row.receiptCostInfo)" :key="item.label" style="margin-top:5px">
                    <div v-if="item.label == '运费'">
                      {{ item.label }}：{{ item.value }}
                    </div>
                    <div v-else>
                      {{ item.label }}：{{ item.value }}
                    </div>
                  </div>
                </div>
                <div v-else>
                  <div v-for="item in formatAmount(scope.row.receiptCostInfo)" :key="item.label">
                    <div v-if="item.label == '运费'">
                      {{ item.label }}：{{ item.value }}
                      <span v-if="scope.row.receiptInfo.discount != 100">
                        (手写折扣：{{ scope.row.receiptInfo.discount + '%' }})
                      </span>
                    </div>
                    <div v-else>
                      {{ item.label }}：{{ item.value }}
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="支付详情">
              <template slot-scope="scope">
                <div
                  v-if="(scope.row.receiptInfo.receiptStatus === '未结清' || scope.row.receiptInfo.receiptStatus === '已退款') && scope.row.receiptRefunds.length > 0">
                  <div> 实收总额：{{ scope.row.receiptInfo.paidAmount }}</div>
                  <div v-if="scope.row.receiptInfo.unPaidAmount > 0"> 挂账金额：{{ scope.row.receiptInfo.unPaidAmount }}
                  </div>
                  <div v-for="item in scope.row.paymentHistory">
                    <div v-if="item.payType && item.payAmount > 0">{{ item.payType }}：{{ item.payAmount }} <span
                        v-if="item.currencyType !== '加元'">(人名币)</span></div>
                    <div v-if="item.useChange && item.changeAmount">零钱：{{ item.changeAmount }}</div>
                    <div v-if="item.useIntegral && item.integralAmount">积分 ：{{ item.integralAmount }}</div>
                  </div>
                  <div v-for="item in scope.row.receiptRefunds"> {{ item.payType }}：{{ item.refundAmount }}(退款)</div>
                </div>
                <div v-if="scope.row.receiptInfo.receiptStatus === '未结清' && scope.row.receiptRefunds.length === 0">
                  <div v-if="scope.row.receiptInfo.unPaidAmount > 0"> 挂账金额：{{ scope.row.receiptInfo.unPaidAmount }}
                  </div>
                  <div v-for="item in scope.row.paymentHistory">
                    <div v-if="item.payType && item.payAmount > 0">{{ item.payType }}：{{ item.payAmount }} <span
                        v-if="item.currencyType !== '加元'">(人名币)</span> </div>
                    <div v-if="item.useChange && item.changeAmount">零钱：{{ item.changeAmount }}</div>
                    <div v-if="item.useIntegral && item.integralAmount">积分 ：{{ item.integralAmount }}</div>
                  </div>
                </div>
                <div v-if="scope.row.receiptInfo.receiptStatus === '未支付'">
                  挂账金额：{{ scope.row.receiptInfo.unPaidAmount }}
                </div>
                <div v-if="scope.row.receiptInfo.receiptStatus === '已结清'">
                  <div v-for="item in scope.row.paymentHistory">
                    <div v-if="item.payType && item.payAmount > 0">{{ item.payType }}：{{ item.payAmount }} <span
                        v-if="item.currencyType !== '加元'">(人名币)</span> </div>
                    <div v-if="item.useChange && item.changeAmount">零钱：{{ item.changeAmount }}</div>
                    <div v-if="item.useIntegral && item.integralAmount">积分 ：{{ item.integralAmount }}</div>
                  </div>
                  <div v-for="item in scope.row.receiptRefunds"> {{ item.payType }}：{{ item.refundAmount }}(退款)</div>
                </div>
                <div v-if="scope.row.receiptInfo.receiptStatus === '未退款'">
                  <div v-for="item in scope.row.paymentHistory">
                    <div v-if="item.payType && item.payAmount > 0">{{ item.payType }}：{{ item.payAmount }} <span
                        v-if="item.currencyType !== '加元'">(人名币)</span></div>
                    <div v-if="item.useChange && item.changeAmount">零钱：{{ item.changeAmount }}</div>
                    <div v-if="item.useIntegral && item.integralAmount">积分：{{ item.integralAmount }}</div>
                  </div>
                  <div>
                    未退款金额：{{ (parseFloat(scope.row.receiptInfo.paidAmount) -
                      parseFloat(scope.row.receiptInfo.receiveAbleAmount)) }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="所属门店" width="200">
              <template slot-scope="scope">
                {{ scope.row.receiptInfo.storeName }}
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="200" sortable prop="receiptInfo.createTime"
              align="center"></el-table-column>
          </el-table>
        </div>
        <!-- 分页区 -->
        <div style="margin-top: 10px">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="currentPage" :page-sizes="[20, 50, 100, 200, 500, 1000]" :page-size="pageSize" background
            :layout="isMobile ? 'prev, pager, next' : 'total, sizes, prev, pager, next, jumper'" :small="isMobile"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 添加修改信息 -->
    <el-dialog :title="title + '收据'" v-dialog-drag :visible.sync="dialogFormVisible" :close-on-click-modal="false"
      width="1200px" @close="restForm">
      <div style="position: relative">
        <el-tabs v-model="activeName" type="card">
          <el-tab-pane label="付款与结算" name="baseForm">
            <my-fieldset title="收据基本信息">
              <div class="base">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">状态</el-col>
                      <el-col :span="14">
                        <span :style="{ color: getInvoiceStatus(baseForm.receiptInfo.receiptStatus) }">{{
                          baseForm.receiptInfo.receiptStatus }}</span>
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">所属货仓</el-col>
                      <el-col :span="14">
                        <el-select filterable style="width: 100%" v-model="baseForm.receiptInfo.storeName"
                          placeholder="请选择">
                          <el-option v-for="item in stores" :key="item.id" :value="item.name"
                            :label="item.name"></el-option>
                        </el-select>
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10">客户</el-col>
                      <el-col :span="14">{{ baseForm.receiptInfo.customerNum }}({{ baseForm.receiptInfo.customerName
                      }})</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">总单数</el-col>
                      <el-col :span="14">{{ baseForm.receiptOrderInfos.length }}</el-col>
                    </el-row>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">收据总额</el-col>
                      <el-col :span="6">{{ baseForm.receiptInfo.totalAmount }}</el-col>
                      <el-col :span="8">
                        <!--                        <el-button @click="dialogFormVisible2 = true; totalAmount = oninput(baseForm.receiptInfo.totalAmount)">修改</el-button>-->
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">预付款总额</el-col>
                      <el-col :span="14">{{ baseForm.receiptInfo.advanceAmount }}</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">实收金额</el-col>
                      <el-col :span="14" style="color: green">{{ baseForm.receiptInfo.paidAmount }}</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">当前汇率</el-col>
                      <el-col :span="14">{{ baseForm.receiptInfo.exchangeRate }}</el-col>
                    </el-row>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">应收金额</el-col>
                      <el-col :span="6" style="color: green">{{ baseForm.receiptInfo.receiveAbleAmount }}</el-col>
                      <el-col :span="8">
                        <!--                        <el-checkbox v-model="baseForm.receiptInfo.maLing"  @change="handleModTotalAmount">抹零</el-checkbox>-->
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">手写折扣(%)</el-col>
                      <el-col :span="10">
                        <el-input v-model="baseForm.receiptInfo.discount"></el-input>
                      </el-col>
                      <el-col :span="4">
                        <!--                        <el-checkbox v-model="baseForm.receiptInfo.useDiscount"></el-checkbox>-->
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">尚未支付金额</el-col>
                      <el-col :span="14">{{ baseForm.receiptInfo.unPaidAmount }}</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="10" class="lable-bg">等于人民币</el-col>
                      <el-col :span="14">￥{{ baseForm.receiptInfo.chyAmount }}</el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </div>
            </my-fieldset>
            <my-fieldset title="付款与结算记录">
              <div style="max-height: 300px;overflow: auto">
                <div v-for="item in baseForm.receiptPaymentHistory" style="line-height: 25px">
                  {{ item.updateTime }} <span style="margin:0 5px">{{ item.content }}</span> {{ item.createUser }}
                </div>
              </div>
            </my-fieldset>
          </el-tab-pane>
          <el-tab-pane label="运单核算" name="receiptCostInfo">
            <my-fieldset title="运单各项费用合计">
              <div class="base">
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="16" class="lable-bg">运费合计</el-col>
                      <el-col :span="8">{{ baseForm.receiptCostInfo.freightAmount }}</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="12" class="lable-bg">商品费合计</el-col>
                      <el-col :span="12">{{ baseForm.receiptCostInfo.goodsAmount }}</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="12" class="lable-bg">保险费合计</el-col>
                      <el-col :span="12">{{ baseForm.receiptCostInfo.insuredAmount }}</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="12" class="lable-bg">包装费合计</el-col>
                      <el-col :span="12">{{ baseForm.receiptCostInfo.packAmount }}</el-col>
                    </el-row>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="16" class="lable-bg">会员等级运费折扣率(%)</el-col>
                      <el-col :span="8">{{ baseForm.receiptCostInfo.vipDisCount != 100 || '无' }}</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="12" class="lable-bg">服务费合计</el-col>
                      <el-col :span="12">{{ baseForm.receiptCostInfo.serviceAmount }}</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="12" class="lable-bg">上门取件费合计</el-col>
                      <el-col :span="12" style="color: green">{{ baseForm.receiptCostInfo.takeOnDoorAmount }}</el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="12" class="lable-bg">拍照费合计</el-col>
                      <el-col :span="12">{{ baseForm.receiptCostInfo.photoAmount }}</el-col>
                    </el-row>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="6">
                    <el-row :gutter="20">
                      <el-col :span="16" class="lable-bg">其他杂费合计</el-col>
                      <el-col :span="8">{{ baseForm.receiptCostInfo.otherAmount }}</el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </div>
            </my-fieldset>
            <el-table :data="baseForm.receiptOrderInfos" border style="margin: 20px 0">
              <el-table-column type="index" label="序号" width="60"></el-table-column>
              <el-table-column label="运单号" prop="orderCode" width="150"></el-table-column>
              <el-table-column label="状态" prop="orderStatus" width="100"></el-table-column>
              <el-table-column label="重量" prop="billingWeight" width="80"></el-table-column>
              <el-table-column label="费用" width="200">
                <template slot-scope="scope">
                  <div style="line-height: 20px" v-for="item in scope.row.orderCosts" :key="item">{{ item }}</div>
                </template>
              </el-table-column>
              <el-table-column label="收件人" prop="receiverName" width="100"></el-table-column>
              <el-table-column label="预付款" prop="advanceAmount" width="100"></el-table-column>
              <el-table-column label="物品内容" min-width="300">
                <template slot-scope="scope">
                  <div style="line-height: 20px" v-for="item in scope.row.orderGoodsContent" :key="item">{{ item }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <my-fieldset title="核算历史记录">
              <div style="max-height: 300px;overflow: auto">
                <div v-for="item in baseForm.receiptOrderHistory" style="line-height: 25px">
                  {{ item.updateTime }} <span style="margin:0 5px">{{ item.content }}</span> {{ item.createUser }}
                </div>
              </div>
            </my-fieldset>
          </el-tab-pane>
        </el-tabs>
        <div style="position: absolute; top: 5px; right: 0">
          <el-link v-if="title != '添加'" type="primary" icon="el-icon-document" disabled
            style="margin-right: 10px; font-size: 26px"><span style="font-size:20px">{{
              this.baseForm.receiptCostInfo.receiptCode }}</span></el-link>
          <el-button type="primary" @click="submit" v-if="title == '添加'">保存收据</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="创建收据" v-dialog-drag :visible.sync="dialogFormVisible1" :close-on-click-modal="false"
      width="800px">
      <el-input placeholder="多个单号换行" type="textarea" :autosize="{ minRows: 15 }" v-model="list"></el-input>
      <div style="margin-top:20px;text-align: right">
        <el-button @click="list = ''">清空</el-button>
        <el-button type="primary" @click="handleCreateInvoice()" v-repeatClick>创建收据</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改收据总额" v-dialog-drag :visible.sync="dialogFormVisible2" :close-on-click-modal="false"
      width="300px" @close="totalAmount = ''">
      <el-input v-model="totalAmount" autofocus></el-input>
      <div style="margin-top:20px;text-align: right">
        <el-button @click="totalAmount = ''">清空</el-button>
        <el-button type="primary" @click="handleModTotalAmount('amount')" v-repeatClick
          v-if="title !== '查看'">确定</el-button>
      </div>
    </el-dialog>
    <div ref="printShow" style="height: 100%" v-show="printShow">
      <div style="min-height:100%;padding:10px 5px;font-weight: unset" class="print-border print-weight"
        v-for="(item, index) in printData" :key="index">
        <div class="print-line-height">
          <div>Flying Parcel Services Inc.</div>
          <div>12100 Vulcan Way, Richmond BC V6V 1J8</div>
          <div>TEL:604-273-1011</div>
        </div>
        <div style="margin-top:10px;padding-right:30px">
          <el-row style="margin-bottom: 30px">
            <el-col :span="9" :offset="6">{{ item.receiptInfo.createTime }}</el-col>
            <el-col :span="9" style="text-align: right">#{{ item.receiptInfo.receiptCode }}</el-col>
          </el-row>
          <el-row v-for="(order, index) in item.orderGoodsInfos" style="margin-top:10px" :key="order.workOrderCode">
            <el-col :span="8">{{ order.workOrderCode }}</el-col>
            <el-col :span="7">{{ order.realWeight }}({{ order.billWeight }})</el-col>
            <el-col :span="9" v-if="order.freight" style="text-align: right">${{ order.freight }}</el-col>
            <el-row v-for="goods in order.workOrderGoodsInfos.filter(item => item.goodsCategory !== '自购商品')"
              :key="goods.id" style="padding:20px 0">
              <el-col :span="20">&nbsp;&nbsp;&nbsp;&nbsp;{{ goods.goodsCategory === '包邮商品' ? '包' : '自' }} {{
                goods.goodsEnglishBrand }} {{ goods.goodsName }} {{ goods.specification }}</el-col>
              <el-col :span="4" style="display: flex;justify-content: space-between">
                <div>{{ goods.buyNum }}</div>
                <div>${{ goods.amount }}</div>
              </el-col>
            </el-row>
          </el-row>
          <el-row style="margin-top:30px">
            <div
              v-if="item.receiptInfo.useDiscount || item.receiptInfo.totalAmount != item.receiptInfo.receiveAbleAmount">
              <div>
                <el-col :span="8">Sub-total</el-col>
                <el-col :span="9" style="text-align: right" :offset="7" class="line-through">
                  ${{ item.receiptInfo.totalAmount }}
                </el-col>
              </div>
              <div v-if="item.receiptInfo.useDiscount" style="padding-top:20px">
                <el-col :span="8" :offset="2">手写折扣 {{ item.receiptInfo.discount + '%' }}</el-col>
                <el-col :span="9" style="text-align: right" :offset="5">
                  ${{ item.receiptInfo.receiveAbleAmount }}
                </el-col>
              </div>
              <div v-else style="padding-top:20px">
                <el-col :span="8" :offset="2">修改应收金额</el-col>
                <el-col :span="9" style="text-align: right" :offset="5">
                  ${{ item.receiptInfo.receiveAbleAmount }}
                </el-col>
              </div>
            </div>
            <div v-else>
              <el-col :span="8">Total</el-col>
              <el-col :span="9" style="text-align: right" :offset="7">
                ${{ item.receiptInfo.totalAmount }}
              </el-col>
            </div>

          </el-row>
          <el-row style="line-height: 30px" v-for="payment in item.paymentHistory" :key="payment.id">
            <el-col :span="8">{{ payment.payType }}</el-col>
            <el-col :span="9" style="text-align: right" :offset="7">+ ${{ payment.payAmount }}</el-col>
          </el-row>
          <el-row style="line-height: 30px" v-for="payment in item.refundHistory" :key="payment.id">
            <el-col :span="8">{{ payment.payType }} 退款</el-col>
            <el-col :span="9" style="text-align: right" :offset="7">- ${{ payment.refundAmount }}</el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

let search = {
  //客户号
  customerNum: '',
  //收据号/运单号/销售单号
  info: '',
  //收据状态
  receiptStatus: '',
  //创建时间
  date: []
}

//基本信息表单
let baseForm = {
  receiptInfo: {
    id: null,
    //收据编号
    receiptCode: '',
    //是否可以手写折扣
    useDiscount: false,
    //预付款金额
    advanceAmount: '',
    //金额折算为人民币金额
    chyAmount: '',
    //客户编号
    customerNum: '',
    //客户名称
    customerName: '',
    //手写折扣
    discount: '',
    //汇率
    exchangeRate: '',
    //是否抹零
    maLing: false,
    //备注
    note: '',
    //实收金额
    paidAmount: '',
    //收据状态
    receiptStatus: '',
    //收据类型
    receiptType: '',
    //应收金额
    receiveAbleAmount: '',
    //门店名称
    storeName: '',
    //收款总额
    totalAmount: '',
    //未支付金额
    unPaidAmount: ''
  },
  //支付信息
  paymentInfo: {
    id: null,
    //结余退款方式
    balanceRefundType: '',
    //是否使用零钱
    useChange: false,
    //零钱
    changeAmount: 0,
    //是否使用积分
    useIntegral: false,
    //积分
    integralAmount: 0,
    //货币类型
    currencyType: '加元',
    //强制结清
    forceCloseReceipt: false,
    //支付金额
    payAmount: 0,
    //付款方式
    payType: '',
    //收据编码
    receiptCode: '',
    //备注
    note: ''
  },
  //付款结算记录
  paymentHistory: [],
  //运单核算
  receiptCostInfo: {
    id: null,
    //运费合计
    freightAmount: '',
    //商品费合计
    goodsAmount: '',
    //保险费合计
    insuredAmount: '',
    //包装费合计
    packAmount: '',
    //会员等级运费折扣
    vipDisCount: '',
    //服务费合计
    serviceAmount: '',
    //上门取件费合计
    takeOnDoorAmount: '',
    //拍照费合计
    photoAmount: '',
    //收据编码
    receiptCode: '',
    //其他杂费合计
    otherAmount: ''
  },
  //运单信息
  receiptOrderInfos: [],
  //核算历史记录
  receiptOrderHistory: [],
  receiptPaymentHistory: []
}

//收据退款
let balanceRefund = {
  payType: '',
  refundAmount: '',
  currencyType: '加元',
  note: '',
  id: 0,
  receiptCode: ''
}

import myHeader from '@/components/pageHEader/pageHeader'
import myFieldset from '../components/myFieldset'
import {
  getReceiptInfo,
  addReceiptInfo,
  modReceiptInfo,
  delReceiptInfo,
  createReceiptInfo,
  getReceiptInfoByCode,
  modReceiptExchange,
  addReceiptInfoPay,
  addReceiptInfoRefund,
  addReceiptOrder,
  getOrder,
  delReciptInfoUnpay,
  printInvoice
} from '@/api/finances/invoice'
import { getCustomer } from "@/api/consumers/customer";
import { getDict } from '@/api/common'

export default {
  name: 'invoice',
  components: {
    myHeader,
    myFieldset
  },
  computed: {
    ...mapGetters(['stores', 'userInfo']),
    isMobile() {
      return window.innerWidth <= 768;
    }
  },
  created() {
    this.getDic('payType').then(resp => {
      this.baseFormOptions.payType = resp.data.records[0].childrenInfo.map(item => item.content).filter(item => item.indexOf('退款') === -1 && item.indexOf('积分') === -1 && item.indexOf('零钱') === -1)
      this.baseFormOptions.balanceRefundType = resp.data.records[0].childrenInfo.map(item => item.content).filter(item => item.indexOf('缴费') === -1 && item.indexOf('积分') === -1 && item.indexOf('收款') === -1)
    })
    getDict('RECEIPT_STATUS').then(resp => {
      this.baseFormOptions.status = resp.data
    })
  },
  data() {
    return {
      pageSize: 20,
      currentPage: 1,
      total: 0,
      data: [],
      //表格选中
      multipleSelection: [],
      //当前行
      currentRow: {},
      //搜索
      search: this.cloneObj(search),
      balanceRefund: this.cloneObj(balanceRefund),
      activeName: 'baseForm',
      //对话框
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      //创建运单
      list: '',
      //修改金额
      totalAmount: '',
      title: '添加',
      baseFormOptions: {
        status: [],
        payType: [],
        balanceRefundType: []
      },
      baseForm: this.cloneObj(baseForm),
      //销售单号，运单号
      orderNum: '',
      //打印
      printShow: false,
      printData: []
    }
  },

  mounted() {
    this.$nextTick(() => {
      this.getInvoice()
    })
    let receiptCode = this.$route.query.receiptCode
    let list = this.$route.query.list
    if (receiptCode) { //修改收据
      this.handleUpdate('mod', receiptCode)
    }
    if (list) {//创建收据
      this.dialogFormVisible1 = true
      this.list = list.split(',').join('\n')
      this.dialogFormVisible1 = true
    }
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val
      this.getInvoice()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getInvoice()
    },
    handleNodeClick(node) {
      this.selectCountry = node.label
      this.getInvoice()
    },
    getAmount(arr) {
      let amount = 0
      arr.forEach(item => {
        amount += parseFloat(item.amount || 0)
      })
      return amount
    },
    formatAmount(receiptCostInfo) {
      let keys = [
        { label: '运费', key: 'freightAmount' },
        { label: '代购', key: 'goodsAmount' },
        { label: '保险', key: 'insuredAmount' },
        { label: '包装', key: 'packAmount' },
        { label: '服务', key: 'serviceAmount' },
        { label: '上门取件', key: 'takeOnDoorAmount' },
        { label: '拍照', key: 'photoAmount' },
        { label: '其他', key: 'otherAmount' },
      ]
      let arr = []
      keys.forEach(item => {
        if (receiptCostInfo[item.key]) {
          arr.push({
            label: item.label,
            key: item.key,
            value: receiptCostInfo[item.key]
          })
        }
      })
      return arr
    },
    //收据状态
    getInvoiceStatus(val) {
      let color
      if (val === '已结清' || val === '已退款') {
        color = 'green'
      } else if (val === '未支付' || val === '未结清') {
        color = '#ff5000'
      } else {
        color = 'red'
      }
      return color
    },
    //重置表单信息
    restForm() {
      this.getInvoice()
      this.$nextTick(() => {
        if (this.$refs.baseForm) this.$refs.baseForm.resetFields()
      })
    },
    //打印运单
    print(val) {
      if (!this.multipleSelection.length) {
        this.tip('请先勾选需要打印的收据单！')
        return
      }
      printInvoice(this.multipleSelection.map((item) => item.receiptInfo.receiptCode)).then(resp => {
        this.printShow = true
        this.printData = resp.data
        this.$nextTick(() => {
          this.$print(this.$refs.printShow)
          this.printShow = false
        })
      })
    },
    modForm(data) {
      let { receiptInfo, paymentHistory, receiptCostInfo, receiptOrderHistory, receiptOrderInfos, receiptPaymentHistory } = data
      this.baseForm = this.cloneObj(baseForm)
      this.balanceRefund = this.cloneObj(balanceRefund)
      this.baseForm.paymentHistory = paymentHistory
      this.baseForm.receiptOrderInfos = receiptOrderInfos
      this.baseForm.receiptOrderHistory = receiptOrderHistory
      receiptPaymentHistory.reverse()
      this.baseForm.receiptPaymentHistory = receiptPaymentHistory
      this.handleModform(receiptInfo, this.baseForm.receiptInfo)
      this.handleModform(receiptCostInfo, this.baseForm.receiptCostInfo)
      this.activeName = 'baseForm'
      this.dialogFormVisible = true
      this.dialogFormVisible1 = false
    },
    handleCreateInvoice() {
      this.title = '添加'
      createReceiptInfo(this.list.split('\n')).then(resp => {
        this.modForm(resp.data)
      })
    },
    handleBeforeUpdate() {
      if (!this.multipleSelection.length) {
        this.tip();
        return;
      }
      if (this.multipleSelection.length > 1) {
        this.tip("只能勾选表格中的一条数据");
        return;
      }
      this.handleUpdate(this.multipleSelection[0])
    },
    //撤销支付
    cancelAble(id, index) {
      delReciptInfoUnpay(id).then(resp => {
        this.$message.success("撤销支付成功！");
        this.currentRow.paymentHistory.splice(index, 1)
      })
    },
    /*
    * @params row 需要修改的行数据
    * @params receiptCode 其他页面跳转过来的参数
    * */
    handleUpdate(row, receiptCode) {
      this.currentRow = row
      this.title = '修改'
      if (receiptCode) {
        getReceiptInfoByCode(receiptCode).then(resp => {
          this.modForm(resp.data)
        })
      } else {
        this.modForm(row)
      }
    },
    //修改金额
    handleModTotalAmount(type) {
      let obj = {
        amount: this.totalAmount || this.baseForm.receiptInfo.totalAmount,
      }
      if (type !== 'amount') {
        if (this.baseForm.receiptInfo.useDiscount) {
          obj.discount = this.baseForm.receiptInfo.discount
        }
        obj.maLing = this.baseForm.receiptInfo.maLing
      }
      modReceiptExchange(this.baseForm.receiptInfo.receiptCode, obj).then(resp => {
        let { advanceAmount, chyAmount, paidAmount, receiveAbleAmount, totalAmount, unPaidAmount } = resp.data
        this.baseForm.receiptInfo.chyAmount = chyAmount
        this.baseForm.receiptInfo.receiveAbleAmount = receiveAbleAmount
        this.baseForm.receiptInfo.unPaidAmount = unPaidAmount
        if (type === 'amount') {
          this.baseForm.receiptInfo.paidAmount = paidAmount
          this.baseForm.receiptInfo.totalAmount = totalAmount
          this.baseForm.receiptInfo.advanceAmount = advanceAmount
        }
        this.dialogFormVisible2 = false
        this.$message.success("修改金额成功！");
      })
    },
    //支付不能超过 未支付金额
    checkPayAmount() {
      let changeAmount = parseFloat(this.baseForm.paymentInfo.changeAmount || '0')
      let useIntegral = parseFloat(this.baseForm.paymentInfo.useIntegral || '0') / 10
      let payAmount = parseFloat(this.baseForm.paymentInfo.payAmount)
      let unPaidAmount = parseFloat(this.baseForm.receiptInfo.unPaidAmount)
      let totalAmount = changeAmount + useIntegral + payAmount
      //判断货币类型
      if (this.baseForm.paymentInfo.currencyType === '加元') {
        if (totalAmount > unPaidAmount) {
          this.$message.error("支付总金额不能大于 '未支付金额'！")
          return false
        }
      } else {
        //人民币计算汇率
        let _unPaidAmount = unPaidAmount * parseFloat(this.baseForm.receiptInfo.exchangeRate)
        let _totalAmount = payAmount + (useIntegral + changeAmount) * parseFloat(this.baseForm.receiptInfo.exchangeRate)
        console.log(_unPaidAmount)
        if (_totalAmount > _unPaidAmount) {
          this.$message.error("支付总金额不能大于 '未支付金额' ！")
          return false
        }
      }
      return true
    },
    //添加支付信息
    addReceiptInfoPay() {
      if (!this.checkPayAmount()) {
        return;
      }
      this.baseForm.paymentInfo.receiptCode = this.baseForm.receiptInfo.receiptCode
      addReceiptInfoPay(this.baseForm.paymentInfo.receiptCode, this.baseForm.paymentInfo).then(resp => {
        this.$message.success("支付成功！");
        this.baseForm.paymentInfo = this.cloneObj(baseForm.paymentInfo)
      })
    },
    //添加退款信息
    addReceiptInfoRefund() {
      this.balanceRefund.receiptCode = this.baseForm.receiptInfo.receiptCode
      addReceiptInfoRefund(this.balanceRefund).then(resp => {
        this.$message.success("退款成功！");
      })
    },
    //使用零钱改变
    handleUseChange(val) {
      if (val) {
        let query = {
          accountOrCustomerNo: this.baseForm.receiptInfo.customerNum,
        };
        getCustomer(query).then((resp) => {
          if (resp.data.records.length) {
            this.baseForm.paymentInfo.changeAmount = resp.data.records[0].balance
          } else {
            this.baseForm.paymentInfo.changeAmount = '0.00'
          }
        });
      } else {
        this.baseForm.paymentInfo.changeAmount = '0.00'
      }
    },
    //使用积分
    handleUseIntegral(val) {
      if (val) {
        let query = {
          accountOrCustomerNo: this.baseForm.receiptInfo.customerNum,
        };
        getCustomer(query).then((resp) => {
          if (resp.data.records.length) {
            this.baseForm.paymentInfo.integralAmount = resp.data.records[0].integral
          } else {
            this.baseForm.paymentInfo.integralAmount = '0'
          }
        });
      } else {
        this.baseForm.paymentInfo.integralAmount = '0'
      }
    },
    getInvoice() {
      let query = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        customerNum: this.userInfo.customerNum,
        receiptStatus: this.search.receiptStatus,
        info: this.search.info,
        startTime: this.search.date[0] ? this.search.date[0] + ' 00:00:00' : '',
        endTime: this.search.date[1] ? this.search.date[1] + ' 23:59:59' : '',
      }
      let rows = this.multipleSelection
      getReceiptInfo(query).then(resp => {
        this.data = resp.data.records
        this.total = resp.data.total;
        this.$nextTick(() => {
          this.setCurrent()
          this.toggleSelection(rows)
        })
      })
    },
    //搜索
    searchPage() {
      this.currentPage = 1
      this.pageSize = 20
      this.getInvoice()
    },
    //页面数据刷新后都会默认选中之前选择的数据
    setCurrent() {
      if (this.currentRow.receiptInfo) {
        let checkRow = this.data.filter(item => item.receiptInfo.id == this.currentRow.receiptInfo.id)
        this.$refs.multipleTable.setCurrentRow(checkRow[0])
      }
    },
    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection()
      rows.forEach(row => {
        let checkRow = this.data.filter(item => item.receiptInfo.id == row.receiptInfo.id)
        if (checkRow.length)
          this.$refs.multipleTable.toggleRowSelection(checkRow[0], true);
      });
    },
    //揽收包裹
    handleAddOrder() {
      getOrder(this.orderNum).then(resp => {
        if (this.title === '添加') {
          this.baseForm.receiptOrderInfos.push(resp.data)
        } else {
          resp.data.receiptCode = this.baseForm.receiptInfo.receiptCode
          addReceiptOrder(resp.data).then(resp => {
            this.modForm(resp.data)
          })
        }
      })
    },
    //删除 运单或者销售单数据
    deleteOrderInfo(index) {
      this.confirm().then(() => {
        if (this.title === '添加') {
          this.baseForm.receiptOrderInfos.splice(index, 1)
        } else {
          delReceiptInfo([this.baseForm.receiptOrderInfos[index].id]).then(resp => {
            this.modForm(resp.data)
          })
        }
      })
    },
    //表格双击修改
    handleRowDbclick(row) {
      this.handleUpdate(row)
    },
    //单击表格
    handleRowClick(row) {
      this.currentRow = row
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    submit() {
      this.$refs['baseForm'].validate((valid) => {
        if (valid) {
          if (!this.checkPayAmount()) {
            return;
          }
          let submit = this.cloneObj(this.baseForm)
          let request
          delete submit.paymentHistory
          delete submit.receiptOrderHistory
          if (this.title === '添加') {
            request = addReceiptInfo
          } else {
            request = modReceiptInfo
          }
          request(submit).then((resp) => {
            this.$message.success(resp.message || "成功");
            this.dialogFormVisible = false;
          });
        } else {
          this.activeName = 'baseForm'
        }
      })
    },
    //查看信息
    view() {
      this.handleBeforeUpdate()
      this.title = '查看'
    },
    //删除
    delInvoice() {
      if (!this.multipleSelection.length) {
        this.tip()
        return
      }
      this.confirm().then(() => {
        delReceiptInfo(this.multipleSelection.map((item) => item.receiptInfo.id)).then(resp => {
          this.$message.success(resp.message || "成功");
          this.getInvoice();
        }
        );
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../styles/_themeify";
@import "../../styles/mobile.scss";

.app-page {
  .search-form {
    @media screen and (max-width: 768px) {
      .el-form-item {
        width: 100%;
        margin-right: 0;
      }
    }
  }

  .el-table {
    @media screen and (max-width: 768px) {
      /deep/ .el-table__row {
        td {
          padding: 5px !important;
        }
      }
    }
  }
}

// 移动端对话框样式优化
.el-dialog {
  @media screen and (max-width: 768px) {
    .el-form {
      .el-form-item {
        margin-bottom: 10px;

        .el-form-item__label {
          float: none;
          text-align: left;
          padding: 0 0 5px;
        }

        .el-form-item__content {
          margin-left: 0 !important;
        }
      }

      .el-input,
      .el-select,
      .el-cascader {
        width: 100%;
      }

      .el-date-picker {
        width: 100% !important;
      }
    }
  }
}

// 移动端基础信息样式优化
.base {
  @media screen and (max-width: 768px) {
    .el-row {
      margin-bottom: 10px !important;

      .el-col {
        width: 100% !important;
        margin-bottom: 5px;

        .lable-bg {
          text-align: left;
          padding-left: 0;
        }
      }
    }
  }
}
</style>
